package util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(filterName = "authFilter", urlPatterns = {"/blog_system/blog_list.html"})
public class AuthFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        // Filter初始化操作
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 检查是否已经登录，如果未登录则重定向到登录页面
        if (!isUserLoggedIn(httpRequest)) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
            return;
        }
        // 合法访问，继续执行Filter链或目标Servlet
        chain.doFilter(request, response);
    }
    public void destroy() {
        // Filter销毁操作
    }
    private boolean isUserLoggedIn(HttpServletRequest request) {
        return request.getSession().getAttribute("user") != null;
    }
}